import React from 'react';
import { CheckTable, CheckTableProps } from '../../../../../components/UILibrary/checkTable';
import { checkPermission, getMenuPermissionMgr, PermissionMgr } from 'permission/Index';
import { PermissionType } from '../../../../schema/PermissionTypes';
import qs from 'query-string';
import Button from 'antd/es/button';
import { LeftOutlined } from '@ant-design/icons';
import { modifyRolePermission } from 'admin/servers/servers';
import { message, Spin } from 'antd';
import { JSONObject } from '../../../../../seats/schema/common';
import { TableProps } from './TableProps';
import '../style.scss';

interface RolePermissionProp {}

interface TableDataInfo {
  propName: string;
  propRef: React.RefObject<CheckTable>;
  propData: CheckTableProps;
}

interface RolePermissionState {
  loading: boolean; // 数据更新中
  tableData?: TableDataInfo[];
}

/**授权条件：不能给其他用户分配自己也没有的权限 */
/**RolePermission-角色功能权限-分配 */
export default class RolePermission extends React.Component<
  RolePermissionProp,
  RolePermissionState
> {
  /**角色id */
  private roleId: number;
  /**角色权限 */
  private rolePermissionMgr: PermissionMgr;

  constructor(prop: RolePermissionProp) {
    super(prop);

    this.state = {
      tableData: undefined,
      loading: false,
    };
    const location = (this.props as any).location;
    this.roleId = parseInt(qs.parse(location.search).roleId as string);

    // 创建角色权限实例：根据roleId获取某个角色的功能权限
    this.rolePermissionMgr = new PermissionMgr(this.roleId);
  }
  componentDidMount() {
    this.rolePermissionMgr.waitFetchPermission().then(() => {
      this.createTableDatas();
    });
  }

  /**更新表格数据*/
  createTableDatas() {
    const tableData: any = [...TableProps].map(item => {
      return {
        propName: item.name,
        propRef: React.createRef(),
        propData: this.createProp(item),
      };
    });

    this.setState({
      tableData,
    });
  }

  /**返回 */
  private goBack = () => {
    (this.props as JSONObject).history.push('/webapp/account/role');
  };
  /**刷新角色权限 */
  private refresh() {
    this.rolePermissionMgr.refreshPermission().then(() => {
      this.createTableDatas();
    });
  }

  /**查询菜单权限id */
  private getKey(type: PermissionType) {
    /**全局菜单权限 */
    return getMenuPermissionMgr().getPermissionId(type) as number;
  }

  /**当前角色选中的权限 */
  private roleCheckPermission(type: PermissionType): boolean {
    return this.rolePermissionMgr.getPermissionId(type) > -1 ? true : false;
  }

  // 生成子节点
  private createChildProp(child: any) {
    return child.map((item: any) => {
      return {
        caption: item.name,
        key: this.getKey(item.path),
        checked: this.roleCheckPermission(item.path),
        disabled: !checkPermission(item.path),
        children: item.children ? this.createChildProp(item.children) : null,
      };
    });
  }

  /**
   * 生成父级节点
   * @param prop 配置信息
   * @param tableHeader 是否显示子菜单标题栏
   * @returns
   */
  private createProp(prop: any): CheckTableProps {
    const option = {
      caption: prop.name,
      key: this.getKey(prop.path),
      checked: this.roleCheckPermission(prop.path),
      disabled: !checkPermission(prop.path),
      children: prop.children ? this.createChildProp(prop.children) : null,
    };
    return {
      option,
      tableHeader1: '二级菜单',
      tableHeader2: '操作',
    };
  }

  private submitData = async () => {
    this.setState({
      loading: true,
    });
    const { tableData } = this.state;
    if (!tableData) return;

    const arr: number[] = [];
    tableData.forEach(item => {
      const values = item.propRef.current?.getValue();
      values?.forEach(val => arr.push(val as number));
    });
    try {
      await modifyRolePermission({
        roleId: this.roleId,
        permissionIds: arr,
      });
      message.success('编辑成功');
      this.refresh();
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    this.setState({
      loading: false,
    });
  };

  render() {
    const { tableData, loading } = this.state;
    return (
      <Spin spinning={!tableData || loading}>
        <div className="role-permission-btngroup">
          <Button type="link" onClick={this.goBack}>
            <LeftOutlined /> 返回
          </Button>
          <Button className="role-permission-btn right" onClick={this.goBack}>
            取消
          </Button>
          <Button className="role-permission-btn right" type="primary" onClick={this.submitData}>
            保存
          </Button>
        </div>
        <div className="role-permission-tableroom">
          {tableData &&
            tableData.map(item => {
              return (
                <CheckTable
                  key={item.propName}
                  ref={item.propRef}
                  option={item.propData.option}
                  tableHeader1={item.propData.tableHeader1}
                  tableHeader2={item.propData.tableHeader2}
                />
              );
            })}
        </div>
      </Spin>
    );
  }
}
